package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-comms/cache"
	"red-book-comms/model"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	book := c.PostForm("book")
	name := c.PostForm("name")

	data := model.User{
		Title: title,
		Book:  book,
		Name:  name,
	}

	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "发布成功",
	})
	return
}
func Del(c *gin.Context) {
	var data []model.User
	id := c.PostForm("id")

	if err := model.DB.Where("id = ?", id).Delete(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "删除失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "删除成功",
	})
	return
}
func Beek(c *gin.Context) {
	id := c.PostForm("id")
	var data []model.User

	if err := model.DB.Where("id = ?", id).First(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"smg":  "查询失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "查询成功",
		"data": data,
	})
	return
}
func List(c *gin.Context) {

	var data []model.User

	redis_list_key := "list_key"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"smg":  "查询成功",
		"data": data,
	})
	return
}
